package com.spring.bean.register;

import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class MyBeanDefinitionPostProcessorRegister implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        BeanDefinitionBuilder beanDefinitionBuilder =  BeanDefinitionBuilder.genericBeanDefinition(Person.class);
        beanDefinitionBuilder.setLazyInit(false);
        beanDefinitionBuilder.setScope(BeanDefinition.SCOPE_SINGLETON);
        beanDefinitionBuilder.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_NO);
        registry.registerBeanDefinition("person", beanDefinitionBuilder.getBeanDefinition());
    }

    @SneakyThrows
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Object object = beanFactory.getBean("person");
        Field[] fields = object.getClass().getDeclaredFields();
        Class c = Integer.class;
        for(Field field : fields){
            field.setAccessible(true);
            Class<?> clazz = field.getType();
            if(clazz.equals(Integer.class)){
                field.set(object, 2);
            }
            if (clazz.equals(String.class)){
                field.set(object, "李四");
            }
        }
    }
}
